package com.bjpowernode.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.bjpowernode.mapper.TClueMapper;
import com.bjpowernode.query.ClueExcel;
import jakarta.annotation.Resource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class ClueExcelListener implements ReadListener<ClueExcel> {

    /**
     * 读取数据的阈值
     * 读取到100条数据之后，一次性的插入到数据库中
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 读取缓存数据的集合
     * 多个用户（线程）可以同时上传文件，所以这里可能会有线程安全问题
     * @param clueExcel
     * @param analysisContext
     */
    private List<ClueExcel> clueDataList = new CopyOnWriteArrayList<>();

    //注意这个不能注入了
    private TClueMapper tClueMapper;

    //当前登录的用户id
    private Integer loginUserId;

    public ClueExcelListener() {

    }

    public ClueExcelListener(TClueMapper tClueMapper, Integer loginUserId) {
        this.tClueMapper = tClueMapper;
        this.loginUserId = loginUserId;
    }


    /**
     * 每读取每一行数据，就会执行一次该方法
     * @param clueExcel
     * @param analysisContext
     */
    @Override
    public void invoke(ClueExcel clueExcel, AnalysisContext analysisContext) {
        clueExcel.setCreateTime(new Date());
        clueExcel.setCreateBy(loginUserId);
        //将读取的数据存储到缓存集合中
        clueDataList.add(clueExcel);

        //判断缓存集合中的数据是否达到阈值，达到则进行批量插入
        if (clueDataList.size() >= BATCH_COUNT) {
            //批量添加数据
            tClueMapper.saveExcel(clueDataList);

            //清空数据
            clueDataList.clear();
        }
    }

    /**
     * 数据读取完毕后，最后执行的方法
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        tClueMapper.saveExcel(clueDataList);
    }
}
